package com.pb.wkflow.core.service.impl;

import com.alibaba.fastjson.JSON;
import com.pb.wkflow.core.service.WorkflowBpmnService;
import com.pb.wkflow.core.utils.StringUtils;
import org.camunda.bpm.model.bpmn.BpmnModelInstance;
import org.camunda.bpm.model.bpmn.instance.ExtensionElements;
import org.camunda.bpm.model.bpmn.instance.FlowElement;
import org.camunda.bpm.model.xml.instance.ModelElementInstance;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author 苗益辉
 * @date 2022/9/28 16:10
 */
@Service
public class WorkflowBpmnServiceImpl implements WorkflowBpmnService {

    private static final String QUOTES = "\"";
    private static final String DOUBLE_QUOTES = "\"\"";

    /**
     * 获取节点自定义属性
     * @param bpmnModelInstance 模型
     * @param taskDefId 节点id
     * @param claz 自定义属性
     * @param clazz 自定义属性
     * @param <T> 自定义属性
     * @return 自定义属性
     */
    @Override
    public <T> T getNodeExtensionProperty(BpmnModelInstance bpmnModelInstance, String taskDefId, Class claz, Class<T> clazz) {
        FlowElement flowElement = bpmnModelInstance.getModelElementById(taskDefId);
        if (flowElement == null) {
            return null;
        }
        ExtensionElements extensionElements = flowElement.getExtensionElements();
        if (extensionElements == null) {
            return null;
        }
        List<ModelElementInstance> modelList = extensionElements.getElementsQuery().filterByType(claz).list();
        if (modelList != null && modelList.size() > 0) {
            ModelElementInstance modelEle = modelList.get(0);
            String text = modelEle.getTextContent();
            if (StringUtils.isNotBlank(text) && !DOUBLE_QUOTES.equals(text)) {
                if (QUOTES.equals(text.substring(0, 1))) {
                    text = trimQuotes(text);
                }
                text = text.replaceAll("\\\\", "");
                if (StringUtils.isNotBlank(text)) {
                    if (clazz == String.class) {
                        return (T) text;
                    } else {
                        return JSON.parseObject(text, clazz);
                    }
                }
            } else {
                return (T) modelEle;
            }
        }
        return null;
    }

    /**
     * 去掉字符串前后双引号
     * @param str 字符串
     * @return String
     */
    private String trimQuotes(String str) {
        if(StringUtils.isNotBlank(str) && str.length() > 0) {
            if (QUOTES.equals(str.charAt(0) + "") && QUOTES.equals(str.charAt(str.length() - 1) + "")) {
                return str.substring(1, str.length() - 1);
            }
        }
        return str;
    }
}
